package com.mazong.servershirobb.config;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class MyShiroConfig {

    //--1 realm
    @Bean
    public MyUserRealm getMyUserRealm() {
        return new MyUserRealm();
    }

    @Bean
    MyCredentialsMatcher getMyCredentialsMatcher() {
        return new MyCredentialsMatcher();
    }

    //--2 securityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager() {
        DefaultWebSecurityManager dwm = new DefaultWebSecurityManager();

        MyUserRealm realm = getMyUserRealm();
        realm.setCredentialsMatcher(getMyCredentialsMatcher());

        dwm.setRealm(realm);

        return dwm;
    }

    //--3 securityFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
        //--1 创建过滤工厂
        ShiroFilterFactoryBean sffb = new ShiroFilterFactoryBean();
        sffb.setSecurityManager(getDefaultWebSecurityManager());

        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         *    常用的过滤器：
         *       anon: 无需认证（登录）可以访问
         *       authc: 必须认证才可以访问
         *       user: 如果使用rememberMe的功能可以直接访问
         *       perms： 该资源必须得到资源权限才可以访问
         *       role: 该资源必须得到角色权限才可以访问
         */
        //-- anon/authc/user/perms/role
        Map<String,String> filerMap = new LinkedHashMap<>();

        //
        filerMap.put("/login", "anon");
        filerMap.put("/logout", "anon");
        filerMap.put("/download/**", "anon");
        filerMap.put("/js/**", "anon");
        filerMap.put("/css/**", "anon");
        filerMap.put("/image/**", "anon");

        //--设置登录url
        sffb.setLoginUrl("/login");
        sffb.setUnauthorizedUrl("/403");
        sffb.setSuccessUrl("/index");

        // 权限设置
        filerMap.put("/product/select", "perms[USER]");
        filerMap.put("/product/insert", "perms[USER]");
        filerMap.put("/product/update", "perms[ADMIN]");
        filerMap.put("/product/delete", "perms[ADMIN]");

        filerMap.put("/**", "authc");

        sffb.setFilterChainDefinitionMap(filerMap);

        return sffb;
    }
}
